//
//  EpointLoginViewController.m
//  EpointFrame5
//
//  Created by 李亚春 on 13-12-5.
//  Copyright (c) 2013年 Epoint. All rights reserved.
//

#import "EpointLoginViewController.h"
#import "UIGlossyButton.h"
#import "EpointUpdateService.h"
#import "EpointNavForPadViewController.h"
#import "EpointMainLoadTask.h"
#import "EpointMainConfigModel.h"
#import "MDUtil.h"
#import "EpointPhoneMainViewController.h"
#import "EpointDbConfig.h"
#import "EpointHomeViewController.h"

#define LoginTaskId 1
#define CheckUpdateTaskId 2
#define GetPadNavInfo 3
#define uploadErrorInfo 4

@interface EpointLoginViewController ()
{
    HJManagedImageV *headImgView;
    HJObjManager *objMan;
    UIView *rootView;
}

@end

@implementation EpointLoginViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        if (CurrentDeviceISiPad) {
            splitVC = [[UISplitViewController alloc] init];
        }
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    if (![[DBFrameService getConfigValue:@"ShowViewPager"]isEqualToString:@"1"]) {
        rootView = self.navigationController.view;
        [self showIntroView];
    }
    
    self.title = @"登录";
    [self initControls];
    [self initHJManage];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasShown:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWasHide:) name:UIKeyboardWillHideNotification object:nil];
    
    btLogin.enabled = YES;
    [btLogin setBackgroundImage:[UIImage imageNamed:@"img_loginbtn_pressed"] forState:UIControlStateHighlighted];
    [self startTask:@"EpointUploadMobileErrorLogTask" withParams:nil withTaskId:uploadErrorInfo];
    
    [self startTask:@"EpointGetOnlineUsers" withParams:nil withTaskId:8];
    
    //        NSException *e = [NSException
    //                          exceptionWithName: @"异常情况1"
    //                          reason: @"number大于10"
    //                          userInfo: nil];
    //        @throw e;
    
//    EpointDbConfig *econfig = [[EpointDbConfig alloc]init];
//    econfig.key = @"EPKEY";
//    econfig.value = @"China Boy";
//    [econfig save];
//    
//    EpointDbConfig *econfig2 = (EpointDbConfig *)[EpointDbConfig findFirstByCriteria:@"WHERE key = 'EPKEY'"];
//    NSLog(@"%@",econfig2.value);
    
}

-(void)showIntroView
{
    NSLog(@"APP高度:%f",AppHeight);
    
    NSArray *imgs = [[NSArray alloc]initWithObjects:@"img_intro_1.jpg",@"img_intro_2.jpg",@"img_intro_3.jpg",@"img_intro_4.jpg", nil];
    
    if (AppHeight>480) {
        imgs = [[NSArray alloc]initWithObjects:@"img_intro_1_a.jpg",@"img_intro_1_b.jpg",@"img_intro_1_c.jpg",@"img_intro_1_d.jpg", nil];
    }
    
    [DBFrameService setConfigValue:@"ShowViewPager" value:@"1"];
    EAIntroPage *page1 = [EAIntroPage page];
    page1.bgImage = [UIImage imageNamed:[imgs objectAtIndex:0]];
    
    EAIntroPage *page2 = [EAIntroPage page];
    page2.bgImage = [UIImage imageNamed:[imgs objectAtIndex:1]];
    
    EAIntroPage *page3 = [EAIntroPage page];
    page3.bgImage = [UIImage imageNamed:[imgs objectAtIndex:2]];
    
    EAIntroPage *page4 = [EAIntroPage page];
    page4.bgImage = [UIImage imageNamed:[imgs objectAtIndex:3]];
    
    EAIntroView *intro = [[EAIntroView alloc] initWithFrame:rootView.bounds andPages:@[page1,page2,page3,page4]];
    [intro setDelegate:self];
    
    [intro showInView:rootView animateDuration:0.3];
}

//初始化图片缓存管理器
-(void)initHJManage
{
    objMan = [[HJObjManager alloc] initWithLoadingBufferSize:20 memCacheSize:30];
    NSString* cacheDirectory = [NSHomeDirectory() stringByAppendingString:@"/Library/Caches/imgcache/flickr/"] ;
    HJMOFileCache* fileCache = [[HJMOFileCache alloc] initWithRootPath:cacheDirectory];
    objMan.fileCache = fileCache;
    fileCache.fileCountLimit = 100;
    fileCache.fileAgeLimit = 60*60*24*30; //1 week
    [fileCache trimCacheUsingBackgroundThread];
}

- (void) keyboardWasShown:(NSNotification *) notif{
    NSDictionary *info = [notif userInfo];
    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGSize keyboardSize = [value CGRectValue].size;
    CGFloat keyHeight = keyboardSize.height;
    if (CurrentDeviceISiPad) {
       keyHeight = IsiOS8Over?keyboardSize.height:keyboardSize.width;
    }
    
    CGFloat vy = AppHeight - keyHeight-vLoginPanel.frame.size.height;
    [UIView animateWithDuration:0.3f animations:^{
        [vLoginPanel setFrame:CGRectMake(vLoginPanel.frame.origin.x, vy, vLoginPanel.frame.size.width, vLoginPanel.frame.size.height)];
    }];
}

- (void) keyboardWasHide:(NSNotification *) notif
{
    [UIView animateWithDuration:0.3f animations:^{
        vLoginPanel.center = CGPointMake(self.view.center.x, AppHeight/2);
    }];
    
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [tfLoginId resignFirstResponder];
    [tfPsw resignFirstResponder];
}

-(void)initControls
{
    [self.customBackground setImage:[UIImage imageNamed:@"img_login_bg.jpg"]];
    self.navigationItem.leftBarButtonItem = nil;
    [self.navigationItem setHidesBackButton:YES];
    
    tfLoginId = [[JYTextField alloc]initWithFrame:CGRectMake(10, 116, 260, 38)
                                      cornerRadio:5
                                      borderColor:COLOR(166, 166, 166)
                                      borderWidth:2
                                       lightColor:COLOR(55, 154, 255)
                                        lightSize:8
                                 lightBorderColor:COLOR(235, 235, 235)];
    tfLoginId.placeholder = @"用户名";
    tfLoginId.autocorrectionType = UITextAutocorrectionTypeNo;
    tfLoginId.autocapitalizationType = UITextAutocapitalizationTypeNone;
    tfLoginId.keyboardType = UIKeyboardAppearanceDefault;
    tfLoginId.clearButtonMode = UITextFieldViewModeWhileEditing;
    [tfLoginId addTarget:self action:@selector(backgroundTap:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [tfLoginId addTarget:self action:@selector(changeHeadImage:) forControlEvents:UIControlEventEditingDidEnd];
    tfLoginId.returnKeyType = UIReturnKeyNext;
    tfLoginId.tag = 1001;
    [vLoginPanel addSubview:tfLoginId];
    
    
    
    tfPsw = [[JYTextField alloc]initWithFrame:CGRectMake(10, 166, 260, 38)
                                  cornerRadio:5
                                  borderColor:COLOR(166, 166, 166)
                                  borderWidth:1
                                   lightColor:COLOR(55, 154, 255)
                                    lightSize:8
                             lightBorderColor:COLOR(235, 235, 235)];
    
    tfPsw.clearButtonMode = UITextFieldViewModeWhileEditing;
    tfPsw.tag = 1002;
    tfPsw.placeholder = @"密码";
    tfPsw.secureTextEntry = YES;
    tfPsw.returnKeyType = UIReturnKeyGo;
    [tfPsw addTarget:self action:@selector(backgroundTap:) forControlEvents:UIControlEventEditingDidEndOnExit];
    [vLoginPanel addSubview:tfPsw];
    
    //    ivHead.layer.masksToBounds = YES;
    //    ivHead.layer.cornerRadius = ivHead.frame.size.height/2;
    //    ivHead.layer.borderWidth = 2;
    //    [ivHead.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    
    //头像
    CGFloat ivLength = 80;
    headImgView = [[HJManagedImageV alloc]initWithFrame:CGRectMake(100,0,ivLength,ivLength)];
    [vLoginPanel addSubview:headImgView];
    
   [headImgView setImage:[UIImage imageNamed:@"img_man.png"]];
    [headImgView.imageView setContentMode:UIViewContentModeScaleToFill];
    headImgView.layer.masksToBounds = YES;
    headImgView.layer.cornerRadius = ivLength/2;
    headImgView.layer.borderWidth = 2;
    [headImgView.layer setBorderColor:[[UIColor whiteColor] CGColor]];
    
    
    
    
    vLoginPanel.center = CGPointMake(self.view.center.x, AppHeight/2);
    
    lbInfo.backgroundColor = [UIColor clearColor];
    lbInfo.font = [UIFont systemFontOfSize:14];
    lbInfo.textColor = [UIColor whiteColor];//COLOR(128, 136, 149);
    lbInfo.textAlignment = NSTextAlignmentCenter;
    lbInfo.shadowColor = [UIColor blackColor];
    lbInfo.shadowOffset = CGSizeMake(0, 1);
}

-(void)textFieldDidEndEditing:(UITextField *)textField
{
    [self backgroundTap:textField];
}

-(void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = YES;
    [super viewWillAppear:animated];
    [self getUserInfo];
    
    [self setHeadImg];
    
    [self startTask:@"EpointCheckUpdateTask" withParams:nil withTaskId:CheckUpdateTaskId];
}

- (void)changeHeadImage:(UITextField *)sender {
    [self setHeadImg];
}

#pragma mark 设置头像
-(void)setHeadImg{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSString *syndate = [ud objectForKey:Epoint_Syn_Date];
    if (syndate.length!=0) {
        if (tfLoginId.text.length==0) {
            [headImgView setImage:[UIImage imageNamed:@"img_woman.png"]];
            return;
        }
        NSString *userguid = [DBFrameService getUserGuidByLoginId:tfLoginId.text];
        if(userguid!=nil && userguid.length>0){
            headImgView.url = [NSURL URLWithString:[EpointBizTools getUserHeadImageDataUrl:userguid]];
        }else{
            [headImgView setImage:[UIImage imageNamed:@"img_woman.png"]];
        }
        
    }
    
    [objMan manage:headImgView];
    
}

- (void)backgroundTap:(UITextField *)sender {
    //    [sender resignFirstResponder];
    if (sender.tag==1002) {
        [self loginAction:sender];
    }else if(sender.tag==1001)
    {
        [tfPsw becomeFirstResponder];
    }
}

- (IBAction)loginAction:(id)sender {
    [tfLoginId resignFirstResponder];
    [tfPsw resignFirstResponder];
    [self startLogin];
}



- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    tfLoginId = nil;
    tfPsw = nil;
    btLogin = nil;
    vLoginPanel = nil;
    lbInfo = nil;
    [super viewDidUnload];
}

-(void)refreshUIWithThreadGuid:(int)taskId andData:(NSObject *)obj
{
    
    if (taskId==LoginTaskId)
    {
        [self hideMBPHUD];
        [self validateDnet:obj];
    }
    else if(taskId==CheckUpdateTaskId)
    {
        BOOL must = [EpointUpdateService validateUpdateInfo:obj vc:self flag:0];
        btLogin.enabled = !must;
        if (must)
        {
            [btLogin setTitle:@"必须更新到最新版客户端才能使用！" forState:UIControlStateNormal];
            [btLogin setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        }
        
    }else if (taskId==GetPadNavInfo) {
        dataArr = (NSMutableArray *)obj;
        [self loadNavViewController];
    }
}

-(void)validateDnet:(NSObject *)obj
{
    NSMutableArray *arr = (NSMutableArray *)obj;
    NSString *isSuccess = [arr objectAtIndex:0];
    if ([isSuccess isEqualToString:@"0"]) {
        [self toastMessage:[arr objectAtIndex:1]];
    }
    else if([isSuccess isEqualToString:@"1"])
    {
        EpointAppDelegate *dele = [[UIApplication sharedApplication]delegate];
        dele.loginVC = self;
        if (!CurrentDeviceISiPad)
        { //如果当前设备是iphone 就改为iphone的nib文件
            //            EpointMainLoadViewController *vc = [[EpointMainLoadViewController alloc]init];
            //           [self.navigationController pushViewController:vc animated:YES];
            EpointPhoneMainViewController *vc = [[EpointPhoneMainViewController alloc]init];
            [self.navigationController pushViewController:vc animated:YES];
        }else{
            //显示pad导航
            [self showPadViewController];
        }
    }
}

-(void)showPadViewController{
    NSString *bs = [[NSUserDefaults standardUserDefaults]objectForKey:Epoint_User_MainConfig];
    if (bs==nil) {
        [self startTask:@"EpointMainLoadTask" withParams:nil withTaskId:GetPadNavInfo];
    }else{
        bs = [[NSUserDefaults standardUserDefaults]objectForKey:Epoint_User_MainConfig];
        dataArr = [EpointMainLoadTask getArray:bs default:@"1"];
        [self loadNavViewController];
    }
}

-(void)loadNavViewController{
//    EpointNavForPadViewController* vc = [[EpointNavForPadViewController alloc] initWithNibName:@"EpointNavForPadViewController" bundle:nil];
//    XAppDelegate.window.rootViewController =vc;//XAppDelegate.stackController;
    
    EpointHomeViewController*vc = [[EpointHomeViewController alloc] initWithNibName:@"EpointHomeViewController" bundle:nil];
    [self setModalTransitionStyle:UIModalTransitionStyleFlipHorizontal];
    [self presentViewController:vc animated:YES completion:nil];
    
    
}

-(void)getUserInfo
{
    
    tfLoginId.text = [DBFrameService getSecurityValue:Epoint_User_LoginId];
    tfPsw.text = [DBFrameService getSecurityValue:Epoint_User_Psw];
    if (tfPsw.text.length!=0&&tfLoginId.text.length!=0) {
        [self startLogin];
    }
    
}

-(void)startLogin
{
    if (tfLoginId.text.length==0||tfPsw.text.length==0) {
        [self toastMessage:@"用户名和密码不能为空！"];
        return;
    }
    
    [self showMBPHUD];
    NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
    [params setObject:tfLoginId.text forKey:@"loginid"];
    [params setObject:tfPsw.text forKey:@"psw"];
    [self startTask:@"EpointDWS_CheckLoginTask" withParams:params withTaskId:LoginTaskId];
}

@end
